package cn.edu.sdjzu.xg.kcsj.controller.basic;

import cn.edu.sdjzu.xg.kcsj.domain.Activity;
import cn.edu.sdjzu.xg.kcsj.service.ActivityService;

import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;

@WebServlet("/activityReadByTI")
public class ActivityReadByTI extends HttpServlet {
    // 记录器，可以控制日志信息输出到控制台，替代输出语句
    private static final Logger log = LogManager.getLogger(ActivityReadByTI.class);
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 读取参数id
        String id_str = request.getParameter("id");
        // 创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        // 如果请求body为空
        if (id_str == null) {
            log.debug("未收到请求信息！");
            respMessage_jsonObj.put("message","未收到请求信息！");
            response.getWriter().println(respMessage_jsonObj);
            return;
        }
        try {
            int id = Integer.parseInt(id_str);
            // 根据id查找
            Collection<Activity> activities = ActivityService.getInstance().findByTI(id);
            respMessage_jsonObj.put("data",activities);
            response.getWriter().println(respMessage_jsonObj);
//            String user_jsonStr = JSON.toJSONString(activity);
//            // 响应到前端
//            response.getWriter().println(user_jsonStr);
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            response.getWriter().println(respMessage_jsonObj);
            // 在命令行打印异常信息在程序中出错的位置及原因
            e.printStackTrace();
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            response.getWriter().println(respMessage_jsonObj);
            // 在命令行打印异常信息在程序中出错的位置及原因
            e.printStackTrace();
        }
    }
}
